package cn.jiedh.app.meiweidk.login;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

//import com.cmic.sso.sdk.auth.AuthnHelper;
//import com.cmic.sso.sdk.auth.TokenListener;
import com.houhan.yijianlogin.AuthnHelperUtils;
import com.houhan.yijianlogin.Constant;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;
import org.xutils.ex.HttpException;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jiedh.app.meiweidk.MainActivity;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.Utils.UI.AlertDialog;
import cn.jiedh.app.meiweidk.Utils.UI.MyTBView;
import cn.jiedh.app.meiweidk.Utils.event.EventScreen;
import cn.jiedh.app.meiweidk.Utils.event.EventUtils;
import cn.jiedh.app.meiweidk.Utils.tool.ActivityUtil;
import cn.jiedh.app.meiweidk.Utils.tool.L;
import cn.jiedh.app.meiweidk.Utils.tool.LocationUtil;
import cn.jiedh.app.meiweidk.Utils.tool.MobileUtils;
import cn.jiedh.app.meiweidk.Utils.tool.SPUtils;
import cn.jiedh.app.meiweidk.Utils.tool.StringUtil;
import cn.jiedh.app.meiweidk.Utils.tool.T;
import cn.jiedh.app.meiweidk.Utils.tool.UrlUtils;
import cn.jiedh.app.meiweidk.Utils.tool.ValidateUtils;
import cn.jiedh.app.meiweidk.base.BaseActivity;
import cn.jiedh.app.meiweidk.entity.LoginAndRegisterBean;
import cn.jiedh.app.meiweidk.entity.UserBean;
import cn.jiedh.app.meiweidk.login.anim.NumAnim;
import cn.jiedh.app.meiweidk.login.view.MyCustomView;
import cn.jiedh.app.meiweidk.network.ResponseFailure;
import cn.jiedh.app.meiweidk.network.ResponseSuccess;
import cn.jiedh.app.meiweidk.register.UserAgreementActivity;
import cn.jiedh.app.meiweidk.response.BaseResponse;
import cn.jiedh.app.meiweidk.runtimepermissions.PermissionsManager;
import cn.jiedh.app.meiweidk.runtimepermissions.PermissionsResultAction;
import cn.jiedh.app.meiweidk.welcome.SwitchStauts;
import cn.jpush.android.api.JPushInterface;

/**
 * @name：登陆Activity
 * @author： 司马林
 * @phone： 18423134135
 * @createTime： 2017/10/19
 * @modifyTime： 2017/10/19
 * @explain：
 */
public class LoginActivity extends BaseActivity {

    public static final int RESULT_CODE = 0;

    @BindView(R.id.phone_edt)
    EditText phoneEdt;
    @BindView(R.id.verification_edt)
    EditText verificationEdt;
    @BindView(R.id.verification_btn)
    MyTBView verificationBtn;
    @BindView(R.id.immediately_btn)
    Button immediatelyBtn;
    @BindView(R.id.sel_agree_protocol)
    CheckBox selAgreeProtocol;
    @BindView(R.id.registration)
    TextView registration;


//    @BindView(R.id.login_layout)
//    LinearLayout login_layout;
//    @BindView(R.id.bar_tv_title)
//    TextView title;
//    @BindView(R.id.login_vp)
//    ViewPager vp;
//    @BindView(R.id.login_tab)
//    TabLayout tab;
//    @BindView(R.id.statelayout)
//    StateLayout statelayout;


    //private List<Fragment> fragmentList;
    //private FragmentPagerAdapter pageAdapter;
    // private String[] mTitles = new String[]{"验证码登录", "密码登录"};

    private boolean isGoPswLogin = false;
    private boolean isGoMy = false;
//    private AuthnHelper mAuthnHelper;
//    private TokenListener mListener;
    private int tag;
    private int update = 3;
    private String token;
    private boolean isGoHome = false;

    @Override
    protected int getLayoutView() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView(View view) {
//        initYJlogin();
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            isGoMy = bundle.getBoolean("isGoMy");
            update = bundle.getInt("update2login");
            isGoHome = bundle.getBoolean("isGoHome");
        }

//        if (MobileUtils.hasSimCard(this) && update != 3) {
//            getYjlogin();
//        } else {
//            //login_layout.setVisibility(View.VISIBLE);
//        }

        initListener();
        init();


    }


    @OnClick(R.id.registration)
    public void onClicked(View view) {

        switch (view.getId()) {

            case R.id.registration:

                Intent intent = new Intent(this, UserAgreementActivity.class);
                startActivityForResult(intent, 1);

                break;
        }

    }




    //监听输入框输入内容变化
    private void initListener() {

        verificationEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

//                if (phoneEdt != null && !phoneEdt.getText().equals("")){
//
//                    verificationBtn.setEnabled(true);
//                }else {
//
//                    verificationBtn.setEnabled(false);
//                }

                if (verificationEdt != null && phoneEdt != null && verificationEdt.getText().length() == 6
                        && phoneEdt.getText().length() == 11 && selAgreeProtocol.isChecked()) {
                    immediatelyBtn.setEnabled(Boolean.TRUE);
//                    T.showShort("按钮可点击");
                } else {
                    immediatelyBtn.setEnabled(Boolean.FALSE);
//                    T.showShort("按钮不可点击");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        phoneEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {


            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

//                if (phoneEdt != null && !phoneEdt.getText().equals("")){
//
//                    verificationBtn.setEnabled(true);
//                }else {
//
//                    verificationBtn.setEnabled(false);
//                }

                if (verificationEdt != null && phoneEdt != null && verificationEdt.getText().length() == 6
                        && phoneEdt.getText().length() == 11 && selAgreeProtocol.isChecked()) {
                    immediatelyBtn.setEnabled(Boolean.TRUE);
//                    T.showShort("按钮可点击");
                } else {
                    immediatelyBtn.setEnabled(Boolean.FALSE);
//                    T.showShort("按钮不可点击");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //用户协议
        selAgreeProtocol.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (verificationEdt != null && phoneEdt != null && verificationEdt.getText().length() == 6
                        && phoneEdt.getText().length() == 11 && selAgreeProtocol.isChecked()) {
                    immediatelyBtn.setEnabled(Boolean.TRUE);
//                    T.showShort("按钮可点击");
                } else {
                    immediatelyBtn.setEnabled(Boolean.FALSE);
//                    T.showShort("按钮不可点击");
                }
            }
        });

    }

//    /**
//     * 是否开启一键登录
//     */
//    private void getYjlogin() {
//        Map<String, Object> map = new HashMap<>();
//        map.put("type", "1");
//        request(activity, UrlUtils.SwitchStatus, map, true, new ResponseSuccess<SwitchStauts>() {
//            @Override
//            public void onRequestSucceed(BaseResponse<SwitchStauts> response) {
//                if (response.getCode() == 0 && response.getData().isStatus()) {
//                    yjlogin();
//                } else {
//                    //login_layout.setVisibility(View.VISIBLE);
//                }
//            }
//        }, new ResponseFailure() {
//            @Override
//            public void onRequestFailure(HttpException error, String msg) {
//                //login_layout.setVisibility(View.VISIBLE);
//            }
//        });
//    }

    @OnClick({R.id.verification_btn, R.id.immediately_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.verification_btn://获取验证码


                MobclickAgent.onEvent(this, "login_getCode");
                InputMethodManager imm1 = (InputMethodManager) verificationBtn.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm1.hideSoftInputFromWindow(verificationBtn.getWindowToken(), 0);
                SPUtils.saveBuried("login", "0", "登录-获取验证码", "true",
                        "登录", "", "", "");
//                if (StringUtil.isMobileNO(phoneEdt.getText().toString())) {
                if(!StringUtil.isEmpty(phoneEdt.getText().toString())){
                    getSMSVerification(phoneEdt.getText().toString());
//                    verificationBtn.start();
                }else{
                    T.showShortCenterToast("请输入正确的手机号");
                }

//                } else {
//                    T.showShortCenterToast("请输入正确的手机号");
//                }
                break;
            case R.id.immediately_btn://立即申请
                MobclickAgent.onEvent(this, "code_login"); //umeng 登录
                MobclickAgent.onEvent(this, "login"); //umeng 登录
                InputMethodManager imm = (InputMethodManager) immediatelyBtn.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);

                imm.hideSoftInputFromWindow(immediatelyBtn.getWindowToken(), 0);
                //String phone = phoneEdt.getText().toString();
                String phone = phoneEdt.getText().toString();

                String verification = verificationEdt.getText().toString();
                String errorStr = ValidateUtils.verificationLogin(phone, verification);

                if ("".equals(errorStr)) {
                    login(phone, verification);
                } else {
                    T.showShortCenterToast(errorStr);
                }

                break;
        }
    }

    /**
     * 登录接口
     * @param phone
     * @param verification
     */
    private void login(String phone, String verification) {
        showLoadingDialog();
        SPUtils.saveBuried("login", "0", "登录-验证码登录", "",
                "登录", "", "", "");
        Map<String, Object> map = new HashMap<>();
        map.put("phone", phone);

        map.put("authCodePage", verification);
//        map.put("authCodePage", verification);
        map.put("unite", 0);

//        LocationManager locationManager = (LocationManager) this.getApplication().getSystemService(Context.LOCATION_SERVICE);
//        Double[] doubles = LocationUtil.getGpsLocation(this.getApplicationContext(), locationManager);
        Double[] doubles = LocationUtil.location;
        if (doubles != null) {
            Double lat = doubles[0];
            Double lng = doubles[1];
            String latStr = String.valueOf(lat);
            String lngStr = String.valueOf(lng);
            map.put("longitude", latStr);
            map.put("latitude", lngStr);
        }

        request(UrlUtils.VERIFICATIONLOGIN, map, true, new ResponseSuccess<LoginAndRegisterBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<LoginAndRegisterBean> response) {
                dismissLoadingDialog();
                T.showShort(response.getMessage());
                int code = response.getCode();
                Log.d(TAG, "登录返回Code " + response.getCode());
                if (0 == response.getCode()) {

                    String t = response.getData().getToken();
                    SPUtils.saveUser(phone, response.getData().getToken());
                    JPushInterface.setAlias(getApplicationContext(), SPUtils.getPhone(), null);
                    if (isGoHome) {
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("isHome", true);
                        ActivityUtil.next(getApplicationContext(), MainActivity.class, bundle);
                        EventScreen eventScreen = new EventScreen(cn.jiedh.app.meiweidk.Utils.event.Constant.NEWUSER, "");
                        EventUtils.getDefault().forward(eventScreen);
                        finish();
                    } else {
                        finish();
                    }
                }
                L.i("token：" + response.getData().getToken());
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                T.showShort(msg);
                dismissLoadingDialog();
            }
        });
    }

    private static final String TAG = "LoginActivity";

    /**
     * 发送验证码
     * @param phone
     */
    private void getSMSVerification(String phone) {
        showLoadingDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("phone", phone);

        //map.put("imgKey", imgKey);
        //map.put("imgCode", imageCodeEdt.getText().toString());
        request(UrlUtils.LOGINSMSCODE, map, true, new ResponseSuccess() {
            @Override
            public void onRequestSucceed(BaseResponse response) {
                Log.d(TAG, "getSMSVerification: " + UrlUtils.LOGINSMSCODE);
                dismissLoadingDialog();

                int code = response.getCode();
                if (0 == response.getCode()) {
                    T.showShort("发送成功");
                    verificationBtn.start();
                }

                if (0 != response.getCode()) {
                    T.showShort(response.getMessage());
                    Log.d(TAG, "response.getMessage()" + response.getMessage());
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                T.showShort(msg);
                dismissLoadingDialog();
            }
        });
    }

//    //预取号
//    public void pregetphone() {
//        tag = 1;
//        showLoadingDialog();
//        AuthnHelperUtils.preGetPhone(mAuthnHelper, mListener, tag);
//    }

    //判断权限
    public void getroot() {
        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(this, new String[]{
                Manifest.permission.READ_PHONE_STATE}, new PermissionsResultAction() {
            @Override
            public void onGranted() {
//                pregetphone();

            }

            @Override
            public void onDenied(String permission) {
                showdialog();
            }
        });
    }

    //未开启权限弹出dialog
    private void showdialog() {
        new AlertDialog(this).builder().setTitle("未开启权限").setMsg("跳转至设置界面").setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        }).setPositiveButton("确定", new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                MobileUtils.getAppDetailSettingIntent(LoginActivity.this);

            }
        }).show();
    }

//    //调起一键登录页面
//    private void yjlogin() {
//        tag = 2;
//        AuthnHelperUtils.displayLogin(mAuthnHelper, mListener, tag);
//    }
//
//    private void initYJlogin() {
//        mAuthnHelper = AuthnHelper.getInstance(this.getApplicationContext());
//        mAuthnHelper.setDebugMode(true);
//        mListener = new TokenListener() {
//            @Override
//            public void onGetTokenComplete(JSONObject jObj) {
//                dismissLoadingDialog();
//                try {
//                    if (jObj != null) {
//                        if (tag == 1) { //预取号请求结果
//                            if (jObj.has("resultCode")) {
//                                if (jObj.getString("resultCode").equals("103000")) {  //成功
//                                    yjlogin();
//                                } else { //失败弹出注册登录dialog
//
////                                    mHandler.sendEmptyMessage(1);
////                                    T.showShortCenterToast(jObj.getString("desc"));
//                                }
//                            }
//                        } else if (tag == 2) { //显示登录
//                            if (jObj.has("resultCode")) {
//                                if (jObj.getString("resultCode").equals("103000")) {  //成功
//                                    if (jObj.has("token")) {
//                                        token = jObj.getString("token");//获取到token调用我们的回调接口
//                                        handler.sendEmptyMessage(0);
//                                    }
//                                } else if (jObj.getString("resultCode").equals("102121")) {//失败弹出注册登录dialog
////                                    mHandler.sendEmptyMessage(1);
////                                    T.showShortCenterToast(jObj.getString("desc"));
//                                    //login_layout.setVisibility(View.VISIBLE);
//                                } else {
//                                    //login_layout.setVisibility(View.VISIBLE);
//                                }
//                            }
//                        }
//
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    //login_layout.setVisibility(View.VISIBLE);
//                }
//
//
//            }
//        };
//
//    }

//    Handler handler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {//ssologin(jObj.getString("token"));
//            super.handleMessage(msg);
//            switch (msg.what) {
//                case 0:
//                    ssologin(token);
//                    break;
//            }
//        }
//    };

    //服务器登录接口
    private void ssologin(String token) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", "");
        map.put("thirdPartyAppId", Constant.APP_ID);
        map.put("thirdPartyToken", token);
        showLoadingDialog();
        request(this, UrlUtils.SSOLOGIN, map, true, new ResponseSuccess<UserBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<UserBean> response) {
                if (response.isSuccess()) {
                    SPUtils.saveUser(response.getData().getPhone(), response.getData().getToken());
                    JPushInterface.setAlias(activity, SPUtils.getPhone(), null);
                    if (isGoHome) {
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("isHome", isGoHome);
                        ActivityUtil.next(activity, MainActivity.class, bundle);
                    }
                    finish();
                    EventScreen eventScreen = new EventScreen(cn.jiedh.app.meiweidk.Utils.event.Constant.NEWUSER, "");
                    EventUtils.getDefault().forward(eventScreen);
                    dismissLoadingDialog();
                } else {
                    T.showShortToast(response.getMessage());
                    //login_layout.setVisibility(View.VISIBLE);
                }

            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                T.showShort(msg);
            }
        });
    }

    public void init() {
        if (getIntent().getExtras() != null) {
            isGoPswLogin = getIntent().getExtras().getBoolean("isGoPswLogin");
        }
//        title.setText("登录");
//        fragmentList = new ArrayList();
//
//        fragmentList.add(new VerificationLoginFragment());
//        fragmentList.add(new PswLoginFragment());
//        initAdapter();

//        tab.setupWithViewPager(vp);
//        tab.getTabAt(0).setText(mTitles[0]);
//        tab.getTabAt(1).setText(mTitles[1]);
        //禁止viewPager滑动
//        vp.setOnTouchListener((v, event) -> true);
        if (isGoPswLogin) {
//            tab.getTabAt(1).select();
        } else {
//            tab.getTabAt(0).select();
        }

    }

    @Override
    public void finish() {
        setResult(RESULT_CODE);
        super.finish();
    }

    @OnClick({R.id.bar_img_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bar_img_back:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    protected void initData() {
    }

//    private void initAdapter() {
//        pageAdapter = new FragmentPagerAdapter(this.getSupportFragmentManager()) {
//            @Override
//            public Fragment getItem(int position) {
//                return fragmentList.get(position);
//            }
//
//            @Override
//            public int getCount() {
//                return fragmentList.size();
//            }
//
//            @Override
//            public CharSequence getPageTitle(int position) {
//                return mTitles[position];
//            }
//        };
//        vp.setAdapter(pageAdapter);
//    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {



//        if (Build.VERSION.SDK_INT >= 21) {
//            View decorView = getWindow().getDecorView();
//            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
//            decorView.setSystemUiVisibility(option);
//            getWindow().setStatusBarColor(Color.TRANSPARENT); //也可以设置成灰色透明的，比较符合Material Design的风格
//        } else {
//
//            //去除标题栏
//            requestWindowFeature(Window.FEATURE_NO_TITLE);
//            //去除状态栏
//            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
//
//        }



//        //去除标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
////        //去除状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);


        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }
}
